using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;

/// <summary>
/// 敌人配置 ScriptableObject
/// 职责：存储游戏中所有可用的敌人数据
/// </summary>
[CreateAssetMenu(fileName = "EnemyConfig", menuName = "山中战纪/敌人配置")]
public class EnemyConfig : ScriptableObject
{
    [Header("敌人数据库")]
    [SerializeField]
    private List<EnemyConfigData> allEnemies = new List<EnemyConfigData>();

    // 缓存字典以便快速查找
    private Dictionary<string, EnemyConfigData> _enemyDatabase;

    /// <summary>
    /// 初始化数据库（字典）
    /// </summary>
    private void OnEnable()
    {
        BuildDatabase();
    }

    private void BuildDatabase()
    {
        _enemyDatabase = new Dictionary<string, EnemyConfigData>();
        foreach (var enemy in allEnemies)
        {
            if (enemy == null) continue;

            if (!_enemyDatabase.ContainsKey(enemy.enemyId))
            {
                _enemyDatabase.Add(enemy.enemyId, enemy);
            }
            else
            {
                Debug.LogWarning($"[EnemyConfig] 敌人ID重复: {enemy.enemyId}");
            }
        }
    }

    /// <summary>
    /// 根据ID获取敌人配置数据
    /// </summary>
    public EnemyConfigData GetEnemyData(string enemyId)
    {
        if (_enemyDatabase == null || _enemyDatabase.Count == 0)
        {
            BuildDatabase();
        }

        if (_enemyDatabase.TryGetValue(enemyId, out EnemyConfigData data))
        {
            return data;
        }

        Debug.LogError($"[EnemyConfig] 未找到ID为 {enemyId} 的敌人数据");
        return null;
    }

    /// <summary>
    /// 根据配置数据创建敌人实例
    /// </summary>
    public EnemyData CreateEnemyInstance(string enemyId, Transform parent = null)
    {
        var configData = GetEnemyData(enemyId);
        if (configData == null || configData.enemyPrefab == null)
        {
            Debug.LogError($"[EnemyConfig] 无法创建敌人实例，配置数据或预制体为空: {enemyId}");
            return null;
        }

        GameObject enemyObj = Instantiate(configData.enemyPrefab, parent);
        EnemyData enemyData = enemyObj.GetComponent<EnemyData>();

        if (enemyData != null)
        {
            // 初始化敌人数据
            enemyData.InitializeFromConfig(configData);
        }

        return enemyData;
    }

    /// <summary>
    /// 获取所有敌人的配置数据（用于图鉴等）
    /// </summary>
    public List<EnemyConfigData> GetAllEnemies()
    {
        return allEnemies;
    }

    /// <summary>
    /// 在编辑器中添加新的敌人配置
    /// </summary>
    public void AddEnemy(EnemyConfigData newEnemy)
    {
        if (newEnemy != null && !allEnemies.Contains(newEnemy))
        {
            allEnemies.Add(newEnemy);
            BuildDatabase();
        }
    }

    /// <summary>
    /// 在编辑器中移除敌人配置
    /// </summary>
    public void RemoveEnemy(string enemyId)
    {
        var enemyToRemove = allEnemies.FirstOrDefault(e => e.enemyId == enemyId);
        if (enemyToRemove != null)
        {
            allEnemies.Remove(enemyToRemove);
            BuildDatabase();
        }
    }

    /// <summary>
    /// 在编辑器中重新构建数据库
    /// </summary>
    public void RefreshDatabase()
    {
        BuildDatabase();
        Debug.Log($"[EnemyConfig] 数据库已刷新，共 {_enemyDatabase.Count} 个敌人");
    }

    /// <summary>
    /// 验证配置数据
    /// </summary>
    public void ValidateConfig()
    {
        var duplicateIds = allEnemies
            .GroupBy(e => e.enemyId)
            .Where(g => g.Count() > 1)
            .Select(g => g.Key)
            .ToList();

        if (duplicateIds.Count > 0)
        {
            Debug.LogError($"[EnemyConfig] 发现重复的敌人ID: {string.Join(", ", duplicateIds)}");
        }

        var missingPrefabs = allEnemies.Where(e => e.enemyPrefab == null).ToList();
        if (missingPrefabs.Count > 0)
        {
            Debug.LogError($"[EnemyConfig] 以下敌人缺少预制体引用: {string.Join(", ", missingPrefabs.Select(e => e.enemyId))}");
        }
    }
}